package com.jackrain.nea.fc.dl.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.config.Resources;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsDlPurRetQueryCmd;
import com.jackrain.nea.fc.dl.mapper.WMSDLUpdateMapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.QueryCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;

/**
 * 采购退货单提交， 退货仓为WMS管控仓
 *
 * @author kangcong
 * @date 2018/10/24
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsDlPurRetQueryCmdImpl extends CommandAdapter implements WmsDlPurRetQueryCmd {

    @Reference(version = "2", group = "cp")
    private QueryCmd queryCmd;

    @Autowired
    QueryCpUtil postQueryEvemt;

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WMSDLUpdateMapper wmsDlUpdateMapper = ApplicationContextHandle.getBean(WMSDLUpdateMapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("WmsDlPurRetQueryCmdImpl--param-->{}",param);

        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！" + map);
        }
        JSONArray dataArray = param.getJSONArray("IDS");
        JSONArray fixArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject fixcolumn = new JSONObject();
            Long idStr = dataArray.getLongValue(i);
            //查询主表
            HashMap mainMap = wmsDlUpdateMapper.selectWmsPurRet(idStr);
            log.debug("WmsDlPurRetQueryCmdImpl-->mainMap-->{}",mainMap);
            if (mainMap == null) {
                log.debug("WmsDlPurRetQueryCmdImpl-->mainMap=null-->{}","采购退货单提交toWMS，数据为空，idStr=" + idStr);
//                log.debug("采购退货单提交toWMS，数据为空，idStr=" + idStr);
                continue;
            }

            JSONObject mainJo = new JSONObject(mainMap);
            log.debug("WmsDlPurRetQueryCmdImpl-->mainJo-->{}",mainJo);
            //跨库查询发货店仓是否是wms管控
            Long storeecode = mainJo.getLong("orig_ecode");
            String wms_store_ecode = null;
            if (null != storeecode) {
                JSONObject whereJo = new JSONObject();
                whereJo.put("ECODE", storeecode);
                JSONObject result = postQueryEvemt.queryCP("CP_C_STORE", "ISWMS,WMS_STORE_ECODE", whereJo);
                wms_store_ecode = result.getString("WMS_STORE_ECODE");
                if (result != null) {
                    String iswms = TypeUtils.castToString(result.getString("ISWMS"));
                    if (!"1".equals(iswms)) {
                        vh.put("code", 2);
                        vh.put("message", Resources.getMessage("采购退货单不满足 发货方为WMS管控！"));
                        return vh;
                    }
                } else {
                    vh.put("code", -1);
                    vh.put("message", Resources.getMessage("根据发货仓编码未查寻到店仓" + storeecode));
                    return vh;
                }
            }
            //WMS仓库编号
//            mainJo.put("bill_date", new Timestamp(mainJo.getLong("bill_date")).toString());
            mainJo.put("wms_store_code", wms_store_ecode);
            mainJo.put("recive_status", 80);
            mainJo.put("write_time", System.currentTimeMillis());

            //查询子表
            List<HashMap> mapList = wmsDlUpdateMapper.selectWmsPurRetItem(idStr);
            JSONArray injsonArray = new JSONArray();
            JSONArray outjsonArray = new JSONArray();
            for (int a = 0; a < mapList.size(); a++) {
                HashMap hashMap = (HashMap) mapList.get(a);
                JSONObject jsonObject = new JSONObject(hashMap);
                jsonObject.put("bill_no", mainJo.getString("bill_no"));
                Long qtybill = jsonObject.getLong("qty_bill");
                //如果通知数量为负数，取绝对值 入库通知
                if (qtybill < 0) {
                    jsonObject.put("qty_bill", Math.abs(qtybill));
                    injsonArray.add(jsonObject);
                } else {
                    outjsonArray.add(jsonObject);
                }
            }

            //如果入库array.size>0 创建一个入库zb对象，添加到集合中
            if (injsonArray.size() > 0) {
                mainJo.put("bill_type", "AI");
                fixcolumn.put("flag", true);
                fixcolumn.put("mainData", mainJo);
                fixcolumn.put("itemData", injsonArray);
                fixArray.add(fixcolumn);
            }
            //如果出库array.size>0 创建一个出库zb对象，添加到集合中
            if (outjsonArray.size() > 0) {
                JSONObject mainJo1  = (JSONObject)mainJo.clone();
                mainJo1.put("bill_type", "AO");
                JSONObject fixcolumn1  = (JSONObject)fixcolumn.clone();
                fixcolumn1.put("flag", false);
                fixcolumn1.put("mainData", mainJo1);
                fixcolumn1.put("itemData", outjsonArray);
                fixArray.add(fixcolumn1);
            }
        }
        vh.put("data", fixArray);
        vh.put("code", 0);
        vh.put("message", Resources.getMessage("成功"));
        return vh;

    }
}
